package com.example.lin.day8_30;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.lin.day8_30.db.HelloWorldOpenHelper;

public class MyCursorAdapter extends CursorAdapter {

    public MyCursorAdapter(Context context) {
        super(context, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    }


    private static class ViewHolder {
        TextView tv_id;
        TextView tv_age;
        TextView tv_height;
        TextView tv_name;
        TextView tv_sex;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.view_list_item_1, parent, false);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.tv_id = view.findViewById(R.id.tv_id);
        viewHolder.tv_age = view.findViewById(R.id.tv_age);
        viewHolder.tv_height = view.findViewById(R.id.tv_height);
        viewHolder.tv_name = view.findViewById(R.id.tv_name);
        viewHolder.tv_sex = view.findViewById(R.id.tv_sex);
        view.setTag(viewHolder);
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ViewHolder vh = (ViewHolder) view.getTag();
        int age = cursor.getInt(cursor.getColumnIndex(HelloWorldOpenHelper.KEY_AGE));
        int id = cursor.getInt(cursor.getColumnIndex(HelloWorldOpenHelper.KEY_ID));
        String name = cursor.getString(cursor.getColumnIndex(HelloWorldOpenHelper.KEY_NAME));
        String sex = cursor.getString(cursor.getColumnIndex(HelloWorldOpenHelper.KEY_SEX));
        double height = cursor.getDouble(cursor.getColumnIndex(HelloWorldOpenHelper.KEY_HEIGHT));
        vh.tv_age.setText(age + "");
        vh.tv_height.setText(height + "");
        vh.tv_sex.setText(sex);
        vh.tv_name.setText(name);
        vh.tv_id.setText(id + "");
    }
}
